package com.hushao.lims.weblims.controller;

import com.hushao.lims.weblims.domain.*;
import com.hushao.lims.weblims.service.*;
import com.hushao.lims.weblims.utils.UserUtil;
import com.hushao.lims.weblims.vo.ResponseData;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 930588706
 * @date 18/1/20
 * 器材
 */
@Controller
@RequestMapping("/equipment")
public class EquipmentController {

    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private EquipmentRepertoryService equipmentRepertoryService;
    @Autowired
    private EquipmentStorageService equipmentStorageService;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private EquipmentCirculateService equipmentCirculateService;
    @Autowired
    private EquipmentApplyService equipmentApplyService;
    @Autowired
    private EquipmentRepairService equipmentRepairService;
    @Autowired
    private EquipmentScrapService equipmentScrappedService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private UserUtil userUtil;

    /**
     * 根据器材名称模糊查询数量大于0的器材（分页）
     * @param equipmentName
     * @param async
     * @param pageable
     * @param model
     * @return
     * @throws Exception
     */
    @ApiOperation(value="查询数量大于0的器材库存（分页）")
    @PreAuthorize("hasAnyAuthority('ROLE_实验室管理员','ROLE_主管')")
    @GetMapping("/repertorys")
    public String repertorys(@RequestParam(value = "equipmentName",required = false,defaultValue = "") String equipmentName,
                             @RequestParam(value = "async",required = false) boolean async,
                             Pageable pageable,
                             Model model)throws Exception{
        Page<EquipmentRepertory> equipmentRepertoryPage=equipmentRepertoryService.listEquipmentByName(equipmentName,pageable);
        List<EquipmentRepertory> equipmentRepertories=equipmentRepertoryPage.getContent();

        model.addAttribute("page",equipmentRepertoryPage);
        model.addAttribute("equipmentRepertories",equipmentRepertories);

        Integer TeacherId= userUtil.isLogged(SecurityContextHolder.getContext().getAuthentication()).getTeacherId();

        //获取数据库的角色而不是获取当前静态登陆角色
        TeacherInfo teacher1=teacherService.getById(TeacherId);
        boolean isBo=false;
        for (GrantedAuthority r:teacher1.getAuthorities()){
            if("ROLE_实验室管理员".equals(r.getAuthority())){
                isBo=true;
                break;
            }
        }
        model.addAttribute("isBo",isBo);
        return async==true?"/equipments/repertories ::#mainContainerRepleace":"equipments/repertories";
    }
    /**
     * 获取器材入库界面
     * @param model
     * @return
     */
    @ApiOperation(value ="获取器材入库界面" )
    @GetMapping("/storage")
    public String storage(Model model){
        model.addAttribute("consumable",new EquipmentInfo(null,null,null,null));
        return "/equipments/add";
    }

    /**
     *  器材入库（待审核）
     * @param equipmentInfo
     * @return
     * @throws Exception
     */
    @PreAuthorize("hasAuthority('ROLE_实验室管理员')")
    @PostMapping("/storage")
    @ResponseBody
    public ResponseData addStorage(EquipmentInfo equipmentInfo, Integer equipmentCount)throws Exception{
        TeacherInfo teacher= userUtil.isLogged(SecurityContextHolder.getContext().getAuthentication());
        EquipmentStorage equipmentStorage=new EquipmentStorage(equipmentInfo,equipmentCount,teacher,null);
        equipmentStorageService.saveEquipmentStorage(equipmentStorage);
        return new ResponseData(true,"等待审核！");

    }

    /**
     * 获取器材借还界面
     * @param equipmentId
     * @param model
     * @return
     */
    @ApiOperation(value ="获取器材借还界面" )
    @PreAuthorize("hasAuthority('ROLE_实验室管理员')")
    @GetMapping("/circulate/{equipmentId}")
    public String circulateInterface(@PathVariable("equipmentId") Long equipmentId, Model model){
        EquipmentInfo equipmentInfo=equipmentService.findOne(equipmentId);
        model.addAttribute("equipment",equipmentInfo);
        return "equipments/circulate";
    }

    /**
     * 器材借还
     * @param equipmentInfo
     * @param equipmentCount
     * @param teacherNumber     借还者
     * @param state
     * @return
     * @throws Exception
     */
    @ApiOperation(value ="器材借还操作服务" )
    @PreAuthorize("hasAuthority('ROLE_实验室管理员')")
    @PostMapping("/circulate")
    @ResponseBody
    public ResponseData circulate(EquipmentInfo equipmentInfo, Integer equipmentCount, String teacherNumber, String state)throws Exception {
        TeacherInfo operator = userUtil.isLogged(SecurityContextHolder.getContext().getAuthentication());
        TeacherInfo teacherInfo = (TeacherInfo) userDetailsService.loadUserByUsername(teacherNumber);
        EquipmentCirculate equipmentCirculate;
        String message;
        switch (state){
            case "0":
                //查询器材申请表中是否有已通过的申请
                List<EquipmentApply> equipmentApplies1 = equipmentApplyService.listEquipmentAndCountAndState(equipmentInfo, equipmentCount, "1");
                if (equipmentApplies1.size() == 0) {
                    throw new Exception("借出失败，没申请此器材或没通过！");
                }
                //借出
                equipmentCirculate = new EquipmentCirculate(equipmentInfo, equipmentCount, operator, teacherInfo, state, null);
                equipmentCirculateService.loan(equipmentCirculate, equipmentApplies1);
                message = "借出成功！";
                break;
            case "1":
                List<EquipmentApply> equipmentApplies2= equipmentApplyService.listEquipmentAndGiveBackAndState(equipmentInfo, teacherInfo, "3");
                if (equipmentApplies2.size() == 0) {
                    throw new Exception("归还失败,此教师没申请过并借出器材");
                }
                //归还
                equipmentCirculate = new EquipmentCirculate(equipmentInfo, equipmentCount, operator, teacherInfo, state, null);
                equipmentCirculateService.giveBack(equipmentCirculate, equipmentApplies2);
                message = "归还成功！";
                break;
            default: throw new Exception("错误,请正确选择借出/归还选项！");
        }
        return new ResponseData(true, message);
    }

    /**
     * 获取器材报修界面
     * @param equipmentId
     * @param model
     * @return
     */
    @ApiOperation(value ="获取器材报修界面" )
    @PreAuthorize("hasAuthority('ROLE_实验室管理员')")
    @GetMapping("/repairs/{equipmentId}")
    public String repairsInterface(@PathVariable("equipmentId") Long equipmentId, Model model){
        EquipmentInfo equipmentInfo=equipmentService.findOne(equipmentId);
        model.addAttribute("equipment",equipmentInfo);
        return "equipments/repairs";
    }

    /**
     *  器材报修
     * @param equipmentInfo
     * @param equipmentCount
     * @throws Exception
     * @return
     */
    @ApiOperation(value ="器材报修操作服务" )
    @PreAuthorize("hasAuthority('ROLE_实验室管理员')")
    @PostMapping("/repairs")
    @ResponseBody
    public ResponseData repairs(EquipmentInfo equipmentInfo, Integer equipmentCount)throws Exception{
        TeacherInfo teacher= userUtil.isLogged(SecurityContextHolder.getContext().getAuthentication());
        equipmentRepairService.applyRepais(equipmentInfo,equipmentCount,teacher);
        return new ResponseData(true,"申请保修成功，等待审核！");

    }

    /**
     * 获取器材报废界面
     * @param equipmentId
     * @param model
     * @return
     */
    @ApiOperation(value ="获取器材报废界面" )
    @PreAuthorize("hasAuthority('ROLE_实验室管理员')")
    @GetMapping("/scrapped/{equipmentId}")
    public String scrappedInterface(@PathVariable("equipmentId") Long equipmentId, Model model){
        EquipmentInfo equipmentInfo=equipmentService.findOne(equipmentId);
        model.addAttribute("equipment",equipmentInfo);
        return "equipments/scrapped";
    }

    /**
     * 器材报废
     * @param equipmentInfo
     * @param equipmentCount
     * @return
     * @throws Exception
     */
    @ApiOperation(value ="器材报废操作服务" )
    @PreAuthorize("hasAuthority('ROLE_实验室管理员')")
    @PostMapping("/scrapped")
    @ResponseBody
    public ResponseData scrapped(EquipmentInfo equipmentInfo, Integer equipmentCount)throws Exception{
        TeacherInfo teacher= userUtil.isLogged(SecurityContextHolder.getContext().getAuthentication());
        equipmentScrappedService.applyScrapped(equipmentInfo,equipmentCount,teacher);
        return new ResponseData(true,"请等待审核！");
    }

}
